<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2017/4/18 0018
 * Time: 下午 2:13
 */

namespace app\index\controller;

use app\admin\model\Indent as IndentModel;
use app\admin\model\Product;
use app\admin\model\Specification;
use app\admin\model\User;
use app\index\model\IndentIntegral;
use app\index\model\IntegralUsed;
use app\index\model\PayOrder;
use think\Db;
use think\Request;
use Wxpay\Wechat;
use think\Session;

class Indent extends Common
{
    /**
     * @title   如下的订单是免费领取，则需先判断是否购买了套装
     */
    public function isUser()
    {
        if(Request::instance()->isAjax()){
            $phone = input('get.phone');
            $uid = (new User())->where('u_username',$phone)->value('id');
            $find = (new IndentModel())->where(['i_uid'=>$uid,'i_type'=>2])->find();
            if($find){
                Session::set('phone',$phone);
//                Session::set('userid',$uid);
                $this->success('可购买');
            }else{
                $pid = input('get.pid');
                $url = !empty($pid)?url('Index/prdDetail',['pid'=>$pid]):url('Index/prdDetail');
                $this->error('你需购买套装后方可领取',$url);
            }
        }
    }

    /**
     * @title   下订单
     */
    public function indent()
    {
        if(Request::instance()->isAjax()) {
            $data = Request::instance()->param();
            $user = new User();
            $product = new Product();
            //当有推广人而且推广人有上级经销商时，把经销商id添加到订单表中
            //如已注册过的用户有推荐人或经销商，则优先写入订单，如都为空，则写入推广人的
            if (Session::has('userid')) {
                $fuser = $user->field('p_id,dealer_id')->where('id',Session::get('userid'))->find();
                if($fuser['dealer_id']==0 && $fuser['p_id']==0 && isset($data['p_id'])) {
                    $ret = $this->indentExten($data['p_id']);
                    $data['dealer_id'] = isset($ret['dealer_id'])?$ret['dealer_id']:0;
                    $data['p_id'] = isset($ret['p_id'])?$ret['p_id']:0;
                }else {
                    $data['dealer_id'] = $fuser['dealer_id'];
                    $data['p_id'] = $fuser['p_id'];
                }
            }else if(isset($data['p_id'])){
                $ret=$this->indentExten($data['p_id']);
                $data['dealer_id'] = isset($ret['dealer_id'])?$ret['dealer_id']:0;
                $data['p_id'] = isset($ret['p_id'])?$ret['p_id']:0;
            }

            $data['i_number'] = date('Ymd') . substr(implode(NULL, array_map('ord', str_split(substr(uniqid(), 7, 13), 1))), 0, 8);
            $data['i_price'] = $product->where('id', input('post.i_pid'))->value('p_price');
            $data['create_time'] = time();
            $res = $this->store(new IndentModel(), $data);
            if ($res['status']=='success') {
                $this->success('下单成功', url('indent/pay',['id'=>$res['data']]));
            } else {
                $this->error('下单失败');
            }
        }
    }

    /**
     * @title   获取推广人的信息并返回id和经销商id
     * @param null $pid     推荐人id
     * @param null $type    购买类型
     * @return mixed
     */
    private function indentExten($pid=null){
        $fuser = (new User())->where('id', $pid)->find();
        $data = array();
        if ($fuser['u_type'] == 1) {
            if ($fuser['dealer_id'] != 0) $data['dealer_id'] = $fuser['dealer_id'];
            $data['p_id'] = $fuser['id'];
        } else if ($fuser['u_type'] == 2) {
            $data['dealer_id'] = $fuser['id'];
            $data['p_id'] = 0;
        }
        return $data;
    }

    /**
     * @title   微信支付
     * @param null $id  订单id
     * @return mixed
     */
    public function pay($id=null)
    {
        $indent = new IndentModel();
        if(Request::instance()->isAjax()){
            $data['id']         = input('post.id');
            //如已登录，则使用用户原来的信息，防止填写的信息跟账户信息不符
            if(Session::has('userid')) {
                $user = (new User())->where('id',Session::get('userid'))->find();
                $data['i_uname'] = $user['u_nickname'];
                $data['i_phone'] = $user['u_username'];
            }else{
                $data['i_uname'] = input('post.i_uname');
                $data['i_phone'] = Session::has('phone') ? Session::get('phone') : input('post.i_phone');
            }
            $data['i_detail'] = input('post.province') . input('post.city') . input('post.town') . input('post.address');
            $data['i_uintegral']= input('post.i_uintegral');
//            $data['i_totprice'] = input('post.i_totprice');
            $data['i_totprice'] = 0.1;
            $data['complete'] = 1;
            $res = $this->store(new IndentModel(),$data);
            if($res['status']=='success'){
                if(input('post.i_uintegral')!=''){
                    $this->addii(input('post.id'),input('post.i_uintegral'));
                }
                $payorder = $this->payorder(input('post.id'));
                if($payorder['status']=='success'){
                    $this->success('提交成功',$payorder['url']);
                }else{
                    $this->error($payorder['msg']);
                }
            }
        }else{
            $product = new Product();
            $spec = new Specification();
            $res = $indent::get($id);
            $res['product'] = $product->field('p_name,p_price,p_photo')->where('id',$res['i_pid'])->find();
            if(isset($res['i_spec'])) $res['spec'] = $spec->field('s_name,s_price')->where('id',$res['i_spec'])->find();
            $this->assign('res',$res);

            //获取用户现有的积分
            if(Session::has('userid')){
                $integral = integral(Session::get('userid'),2);
                $this->assign('tz_integral',$integral);
            }
            return $this->fetch('index/order_pay');
        }
    }

    /**
     * @title 下订单时使用积分
     * @param $id   订单id
     * @param $integral 使用的积分
     */
    public function addii($id,$integral)
    {
        $ii = new IntegralUsed();
        $iu['iu_uid'] = Session::get('userid');
        $iu['iu_number'] = date('Ymd') . substr(implode(NULL, array_map('ord', str_split(substr(uniqid(), 7, 13), 1))), 0, 8);
        $iu['iu_mean'] = 1;
        $iu['iu_indentid'] = $id;
        $iu['iu_integral'] = $integral;
        $iu['iu_type'] = 2;
        $iu['create_time'] = time();
        $ii->insert($iu);
    }

    /**
     * @title   每点击一次就生产一条支付记录
     * @param $indent_id
     * @return array
     */
    public function payorder($indent_id=null)
    {
        $indent = new IndentModel();
        if($indent::get($indent_id)) {
            //每点击支付一次就生成一条支付订单数据
            session('pay_id', null);
            $data['indentid'] = $indent_id;
            $data['order'] = date('Ymd').substr(implode(NULL, array_map('ord', str_split(substr(uniqid(), 7, 13), 1))), 0, 8);
            $data['mode'] = 1;
            $res = Db::name('pay_order')->insertGetId($data);
            $appId = v('wechat.appid');
            Wechat::setAppId($appId);
            $url = Wechat::createOauthUrl(url('pay/wechat@' . $_SERVER['HTTP_HOST']), $indent_id . '|' . $res);
            return ['status'=>'success','url'=>$url];
        }else{
            return ['status'=>'error','msg'=>'找不到订单'];
        }
    }

    public function done()
    {
        return $this->fetch('index/indent_result');
    }

    /**
     * @title   全部订单
     * @param null $status  支付状态(0:未支付 1:已支付)
     * @param null $type    发货后的状态(0:未发货 1:已发货 2:已收货)
     * @return mixed
     */
    public function indentList($status=null,$type=null)
    {
        $indent = new IndentModel();
        $product = new Product();
        $spec = new Specification();
        $where['i_uid'] = Session::get('userid');
        $where['complete'] = 1;
        if($status!=null) $where['i_status'] = $status;
        if($type!=null) $where['i_confirm'] = $type;
        $list = $indent->where($where)->order('create_time desc')->select();
        foreach ($list as $key => $value){
           $list[$key]['product']  = $product->field('id,p_name,p_photo,p_price')->where('id',$value['i_pid'])->find();
           if($value['i_spec']!='') $list[$key]['spec']  = $spec->field('id,s_name,s_price')->where('id',$value['i_spec'])->find();
           $list[$key]['express'] = Db::name('logistics')->where('indent_id',$value['id'])->value('indent_id');
        }
        $this->assign('list',$list);
        return $this->fetch('index/order');
    }

    /**
     * @title   查看订单详情
     * @param null $id  订单id
     * @return mixed
     */
    public function indentDetail($id=null)
    {
        $indent = new IndentModel();
        $res = $indent::get($id)->toArray();
        $res['product'] = (new Product())->field('id,p_name,p_price,p_photo')->where('id',$res['i_pid'])->find();
        $res['spec'] = (new Specification())->field('s_name,s_price')->where('id', $res['i_spec'])->find();
        $this->assign('res',$res);
        return $this->fetch('index/order_detail');
    }

    /**
     * @title   使用积分提现
     */
    public function withdrawals()
    {
        $data = Request::instance()->param();
        $data['iu_integral'] = $data['iu_integral']>200?200:$data['iu_integral'];
        $uid = Session::get('userid');
        if($data['iu_type']==1){
            $exchg_time = (new User())->where('id',$uid)->value('exchange_time');
            if(time()<$exchg_time){
                $this->error('未到兑换时间');
            }
            (new User())->where('id',$uid)->setField('exchange_time',strtotime(date('Y-m-d', time()))+2592000);
        }
        $data['iu_uid'] = $uid;
        $data['iu_number'] = date('Ymd').substr(implode(NULL, array_map('ord', str_split(substr(uniqid(), 7, 13), 1))), 0, 8);
        $data['iu_mean'] = 2;
        $data['iu_status'] = 1;
        $data['createtime'] = time();
        $ret = $this->store((new IntegralUsed()),$data);
        if($ret['status']=='success'){
            $this->success('提现成功');
        }else{
            $this->error('提现失败');
        }
    }
}